#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class Computer{
public:
    Computer(const char * brand,double price)
        : _brand(new char[strlen(brand) + 1]())
          , _price(price) // _price = price;
    {
        cout << "Computer(const char *,double)" << endl;
        strcpy(_brand,brand);
    }

    ~Computer(){
        if(_brand){
            delete [] _brand;
            _brand = nullptr;
        }
        cout << "~Computer()" << endl;
    }

    Computer(const Computer & rhs)
        : _brand(new char[strlen(rhs._brand) + 1]())
          , _price(rhs._price)
    {
        strcpy(_brand,rhs._brand);
        cout << "Computer(const Computer&)" << endl;
    }

    Computer & operator=(const Computer & rhs)
    {   
        //自定义的赋值运算符函数的流程
        if(this != &rhs){ //1.考虑自复制情况
            delete [] _brand; //2.回收原本的空间
            _brand = new char[strlen(rhs._brand) + 1]();//3.深拷贝
            strcpy(_brand,rhs._brand);//3.
            _price = rhs._price;
            cout << "Computer & operator=(const Computer&)" << endl;
        }
        /* rhs._price = 1; */
        return *this;//4.返回本对象
    }

    void print(){
        cout << "brand:" << _brand << endl;
        cout << "price:" << _price << endl;
    }

private:
    char * _brand;
    double _price;
};


void test0(){
    Computer pc("Apple",20000);
    Computer pc2("XiaoMi",6000);
    Computer pc3("Huawei",8000);
    pc2 = pc;
    //pc2.operator=(pc);
    pc.print();
}

void test1(){
    Computer pc("Apple",20000);
    pc = pc; //自复制语句是可以通过的
    pc.print();
}

void test(){
    int a = 1;
    int b = 2;
    a = b;
    /* a = a; */
}

int main(void){
    test0();
    return 0;
}
